<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class RoleController extends Controller
{
    //
    public function index(Request $request){
        return view('admin.role.list');
    }
    public function ajax_list(Request $request){

        $model=Role::select('id','name','guard_name','created_at','updated_at')
        ->where('guard_name','web')
        ;

        if($request->searchKey){
            $model=$model->where('name','like', '%'.$request->searchKey.'%');
        }
        $model=$model->paginate($request->limit)
            ->toArray();
        return $this->page_json_render($model);
    }
    //创建
    public function create(Request $request){
        return view('admin.role.edit_add');
    }
    //储存
    public function store(Request $request){
        $name=$request->name;
        $this->filter($request);
        $model=new Role();
        $model->name=$request->name;
        $model->guard_name='user';
        $model->save();
        return redirect()->route('admin.role_index')->with(
            $this->success()
        );
    }
    //编辑
    public function edit(Request $request,$id){
        $model=Role::findOrFail($id);
        return view('admin.role.edit_add',compact('id','model'));
    }
    public function update(Request $request){
        $id=$request->id;
        $this->filter($request);
        $model=Role::findOrFail($id);
        $model->name=$request->name;
        $model->save();
        return redirect()->route('admin.role_index')->with(
            $this->success()
        );
    }
    public function del(Request $request){
        $id=$request->id;
        $model=Role::findOrFail($id);
        $model->delete();
        return $this->del_success();

    }
    //角色权限列表
    public function permission(Request $request,$id){
       $permission= Permission::where('guard_name','web')->get();
       $permission=$permission->groupBy('group_name')->all();
       //查看role权限
        $role=Role::find($id);
       $rolePermission= $role->permissions->pluck('name')->all();

       return view('admin.role.permission',compact('id','permission','rolePermission'));
    }
    //权限储存
    public function permissionStore(Request $request){
        $role=Role::find($request->id);
        $role->syncPermissions($request->permission);
        return redirect()->route('admin.role_index')->with(
            $this->success()
        );
    }
    protected function filter($request){
        $this->validate($request,
            [
                'name'=>'required',
            ]);
    }
}
